package com.dries.security.core.validate.code.impl;

import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import com.dries.security.core.validate.code.captcha.Captcha;
import com.dries.security.core.validate.code.captcha.SysCaptcha;
import com.dries.security.core.validate.code.captcha.ValidateCodeGenerator;
import com.dries.security.core.validate.code.captcha.enums.ValidateCodeType;
import com.dries.security.core.validate.code.exception.ValidateCodeException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.ServletRequestBindingException;
import org.springframework.web.bind.ServletRequestUtils;
import org.springframework.web.context.request.ServletWebRequest;

import javax.annotation.Resource;
import java.util.Map;

/**
 * @Description:
 * @Author ZSY
 * @createTime 2020/9/8 12:57
 */
@Slf4j
public abstract class AbstractValidateCodeProcessor<C extends SysCaptcha> implements Captcha {


    /**
     * 收集系统中所有的 {@link ValidateCodeGenerator} 接口的实现。
     */
    @Resource
    private Map<String, ValidateCodeGenerator> validateCodeGenerators;
    @Resource
    private ValidateCodeMapper validateCodeMapper;

    @Override
    public SysCaptcha render(ServletWebRequest request) throws Exception {
        C validateCode = generate(request);
        SysCaptcha captcha = save(request, validateCode);
        send(request, validateCode);

        return captcha;
    }

    /**
     * 生成校验码
     *
     * @param request
     * @return
     */
    @SuppressWarnings("unchecked")
    private C generate(ServletWebRequest request) {
        String type = getValidateCodeType(request).toString().toLowerCase();
        String generatorName = type + ValidateCodeGenerator.class.getSimpleName();
        ValidateCodeGenerator validateCodeGenerator = validateCodeGenerators.get(generatorName);
        if (validateCodeGenerator == null) {
            throw new ValidateCodeException("验证码生成器" + generatorName + "不存在");
        }
        return (C) validateCodeGenerator.generate(request);
    }

    /**
     * 保存校验码
     *
     * @param request
     * @param validateCode
     */
    private SysCaptcha save(ServletWebRequest request, C validateCode) {

        SysCaptcha code = new SysCaptcha(IdUtil.simpleUUID(),validateCode.getCode(), validateCode.getExpireTime());
        log.info("保存效验码==========》{}", validateCode.getCode());
        validateCodeMapper.save(request, code ,getValidateCodeType(request));

        return code;
    }

    /**
     * 发送校验码，由子类实现
     *
     * @param request
     * @param validateCode
     * @throws Exception
     */
    protected abstract void send(ServletWebRequest request, C validateCode) throws Exception;

    /**
     * 根据请求的url获取校验码的类型
     *
     * @param request
     * @return
     */
    private ValidateCodeType getValidateCodeType(ServletWebRequest request) {
        String type = StrUtil.subBefore(getClass().getSimpleName(), "CodeProcessor", false);
        // String type = StringUtils.substringBefore(getClass().getSimpleName(), "CodeProcessor");
        return ValidateCodeType.valueOf(type.toUpperCase());
    }

    @SuppressWarnings("unchecked")
    @Override
    public void validate(ServletWebRequest request) {

        ValidateCodeType codeType = getValidateCodeType(request);

        C codeInSession = (C) validateCodeMapper.get(request, codeType);

        String codeInRequest;
        try {

            codeInRequest = ServletRequestUtils.getStringParameter(request.getRequest(), codeType.getParamNameOnValidate());

        } catch (ServletRequestBindingException e) {
            throw new ValidateCodeException("获取验证码的值失败");
        }

        if (StrUtil.isBlank(codeInRequest)) {
            throw new ValidateCodeException(codeType + "验证码的值不能为空");
        }

        if (codeInSession == null) {
            throw new ValidateCodeException(codeType + "验证码不存在");
        }

        if (codeInSession.isExpired()) {
            validateCodeMapper.remove(request, codeType);
            throw new ValidateCodeException(codeType + "验证码已过期");
        }

        if (!StrUtil.equals(codeInSession.getCode(), codeInRequest)) {
            throw new ValidateCodeException(codeType + "验证码不匹配");
        }

        validateCodeMapper.remove(request, codeType);

    }

}
